﻿using UnityEngine;
using System.Collections;

public class Boss : Unit {

	public Enemy_Type type;//怪物类型
	public GameObject misslePrefab;//导弹预制体
	public float sCD=10f;//大招CD
	private float fireTimer2 = 0;//第二发弹计时器
	private float fireTimer3 = 0;//导弹发弹计时器

	public Transform firepoint2;//第二发弹点
	public Transform firepoint3;//导弹发弹点
	public Transform battery;//第二发弹器
	public Player target;//玩家目标
	
	private Missile missile;

    protected override void Start()
    {
        base.Start();
        Fly ();
		StartCoroutine (Enter());
	}
	
	
	void Update () {
		if (target == null)
			return;
		Vector3 dir = (target.transform.position-battery.position).normalized;
		battery.rotation = Quaternion.FromToRotation (Vector3.left, -dir);
       
		fireTimer += Time.deltaTime;
		fireTimer2 += Time.deltaTime;
		fireTimer3 += Time.deltaTime;
	}

    //死亡
    public override void Death()
    {
        if (hp <= 0)
        {
            ani.SetTrigger("Death");
            Destroy(this.GetComponent<CircleCollider2D>());
            Destroy(gameObject, 0.3f);
            isDeath = true;
            event_manager.Instance.dispatch_event("BossDie", null);
        }
    }

    void OnTriggerEnter2D(Collider2D other)
	{
        //玩家子弹
		if (other.gameObject.tag=="Bullet") 
		{
			Bullet b=other.GetComponent<Bullet>();
			hp-=b.power;
			Destroy(other.gameObject);
		}
		Death();
	}

    //技能动画帧调用，导弹加载
	public void MissileLoad()
	{
		GameObject g = Instantiate (misslePrefab);
		g.transform.SetParent (firepoint3);
		g.transform.localPosition = Vector3.zero;
		missile = g.GetComponent<Missile> ();
		missile.target = this.target;
	}
    //导弹发射
	public void MissileLaunch()
	{
		missile.Launch ();
		missile.transform.SetParent (null);
	}

    //进场
	IEnumerator Enter()
	{
		transform.position = new Vector3 (15, 0, 0);
		yield return StartCoroutine(MoveTo (new Vector3 (4, 0, 0)));
		yield return StartCoroutine(Attack());
	}

    //移动
	IEnumerator MoveTo(Vector3 pos)
	{
		while (true)
		{
			Vector3 dir = pos - transform.position;
			if(dir.magnitude<0.1)
				break;
			transform.position += dir.normalized * speed * Time.deltaTime;
			yield return null;
		}
	}

    //正常攻击
	IEnumerator Attack()
	{
		while (true)
		{
			Fire();
			Fire2();
			if(fireTimer3>sCD)
			{
				Idle();
				yield return StartCoroutine(Skill());
			}
			yield return null;
		}
	}

    //技能
	IEnumerator Skill()
	{
		yield return new WaitForSeconds (1f);
		ani.SetTrigger("Skill");
		fireTimer3 = 0;
		yield return new WaitForSeconds(1f);
	}

    //第二发射
	public void Fire2()
	{
		if (fireTimer2 > 1 / fireRate) 
		{
			GameObject g=(GameObject)Instantiate(bulletPrefab,firepoint2.transform.position,Quaternion.identity);
			Bullet b=g.GetComponent<Bullet>();
			b.speed=b.speed.magnitude*(target.transform.position-battery.position).normalized;
			fireTimer2=0f;
		}
	}
}
